import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svprogresshud/flutter_svprogresshud.dart';
import 'package:goumao_app/Model/gm_vip_model.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import '../Manager/gm_app_purchase_tool.dart';
import '../Manager/gm_user_manager.dart';
import '../Model/gm_login_user.dart';

class GMVIPCenterScreen extends StatefulWidget {
  const GMVIPCenterScreen({super.key});
  @override
// ignore: library_private_types_in_public_api
  _GMVIPCenterScreenState createState() => _GMVIPCenterScreenState();
}

class _GMVIPCenterScreenState extends State<GMVIPCenterScreen> {
  late int index = 1;
  GMVIPData vipData = GMVIPData();
  late Stream<List<PurchaseDetails>> _purchaseStream;

  void _gmGetVIPDataRequest() async {
    String jsonString =
        await rootBundle.loadString('assets/mydata/gm_hy_data.json');
    Map<String, dynamic> jsonData = json.decode(jsonString);
    var data = GMVIPData.fromJson(jsonData);
    vipData = data;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _gmGetVIPDataRequest();

    _gmStartAppPurchase();
    GMInAppPurchaseTool.listenToPurchaseStream();
    GMInAppPurchaseTool.onPurchaseLoading = _gmOnPurchaseLoading;
    GMInAppPurchaseTool.onPurchaseSuccess = _onGmPurchaseSuccess;
  }

  void _gmOnPurchaseLoading() {
  }

  _gmRefreshBalance(int level) async {
    GMLoginUser user = GMUserManager().user!;
    user.level = level;
    await GMUserManager().saveUser(user);
    setState(() {});
  }

  void _onGmPurchaseSuccess() {
    SVProgressHUD.dismiss();
    GMVIPModel data = vipData.vip![index];

    _gmRefreshBalance(int.parse(data.des!)); // Update the balance here
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('购买成功！恭喜您成为尊贵的${data.name}用户，享受会员专属权益'),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  _gmStartAppPurchase() async {
    if (!await GMInAppPurchaseTool.isAvailable()) {
      print('IAP is not available.');
      return;
    }

    _purchaseStream = GMInAppPurchaseTool.purchaseStream;
    _purchaseStream.listen((purchases) {
      for (var purchase in purchases) {
        print('Purchase Details: $purchase');
        if (purchase.status == PurchaseStatus.purchased) {
          GMInAppPurchaseTool.completePurchase(purchase);
        } else if (purchase.status == PurchaseStatus.error) {
          print('Purchase Error: ${purchase.error}');
          SVProgressHUD.dismiss();
        }
      }
    });
  }

  _gmToBuyProduct(String productId) async {
    SVProgressHUD.show();
    try {
      var productDetails =
          await GMInAppPurchaseTool.getProductDetails([productId]);
      if (productDetails.isNotEmpty) {
        await GMInAppPurchaseTool.buyProduct(productDetails.first);
      } else {
        // SVProgressHUD.dismiss();
      }
    } catch (e) {
      // SVProgressHUD.dismiss();
    } finally {
    }
  }

  @override
  void dispose() {
    GMInAppPurchaseTool.cancelSubscription();
    super.dispose();
  }

  Widget _quanyiItemWidget(GMVIPModel data) {
    return Container(
      height: 80,
      padding: const EdgeInsets.only(bottom: 16, left: 20, right: 20),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            color: const Color(0xffffffff)),
        child: Row(
          children: [
            Image.asset(
              data.path!,
              width: 40,
            ),
            const SizedBox(
              width: 12,
            ),
            Text(
              data.name!,
              style: const TextStyle(
                  color: Color(0xff333333),
                  fontSize: 14,
                  fontWeight: FontWeight.w800),
            )
          ],
        ),
      ),
    );
  }

  Widget _gmVipItemWidget(GMVIPModel vipData, int tag) {
    final double gmItemW = (ScreenUtil().screenWidth - 40 - 24) / 3;
    return InkWell(
      onTap: () {
        setState(() {
          index = tag;
        });
      },
      child: Container(
        width: gmItemW,
        height: gmItemW * 16 / 9,
        decoration: BoxDecoration(
          color: const Color(0xffffffff),
          borderRadius: const BorderRadius.only(
            bottomLeft: Radius.circular(12.0),
            bottomRight: Radius.circular(12.0),
          ),
          border: Border.all(
            color: tag == index
                ? const Color(0xff37A787)
                : const Color(0xffffffff), // 设置边框颜色
            width: 1.0, // 设置边框宽度
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              height: 28,
              alignment: Alignment.center,
              color: const Color(0xff37A787),
              child: Text(
                vipData.name!,
                style: const TextStyle(
                    color: Color(0xffffffff),
                    fontSize: 10,
                    fontWeight: FontWeight.w800),
              ),
            ),
            Text(
              vipData.count!,
              style: const TextStyle(
                  color: Color(0xff333333),
                  fontSize: 14,
                  fontWeight: FontWeight.w500),
            ),
            Text(
              'HK${vipData.price1!.toString()}',
              style: const TextStyle(
                  color: Color(0xff333333),
                  fontSize: 24,
                  fontWeight: FontWeight.w700),
            ),
            Text.rich(
              TextSpan(
                text: 'HK${vipData.price2!.toString()}',
                style: const TextStyle(
                    decoration: TextDecoration.lineThrough,
                    color: Color(0xff888888),
                    fontSize: 12),
              ),
            ),
            const SizedBox(
              height: 8,
            )
          ],
        ),
      ),
    );
  }

  Widget _gmVIPTopWidget(List<GMVIPModel> values) {
    DateTime gmNow = DateTime.now();

    int gmMonth = gmNow.month + 1;
    if (gmMonth > 12) gmMonth = 1;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
          height: 106,
          color: const Color(0xff13392F),
          child: Container(
            padding: const EdgeInsets.fromLTRB(12, 8, 12, 14),
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("assets/images/gm_vip_top_bg@2x.png"),
                    fit: BoxFit.cover)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      index <= (GMUserManager().user!.level-1) ? "您好，尊贵的VIP用户" : values[index].name!,
                      style: TextStyle(
                          color: const Color(0xffffffff),
                          fontSize: index == 0 ? 16 : 20,
                          fontWeight: FontWeight.w900),
                    ),
                    Text(
                      index <= (GMUserManager().user!.level-1)
                          ? "2024/${gmMonth.toString().padLeft(2, '0')}/${gmNow.day}到期"
                          : "开通会员，尽享专属特权",
                      style: const TextStyle(
                          color: Color(0xffffffff),
                          fontSize: 10,
                          fontWeight: FontWeight.w500),
                    )
                  ],
                ),
                Text(
                  GMUserManager().user!.nick,
                  style: const TextStyle(
                      color: Color(0xffffffff),
                      fontSize: 12,
                      fontWeight: FontWeight.w900),
                )
              ],
            ),
          ),
        ),
        Container(
          height: 180,
          padding: const EdgeInsets.fromLTRB(20, 18, 20, 32),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _gmVipItemWidget(values.first, 0),
              _gmVipItemWidget(values[1], 1),
              _gmVipItemWidget(values.last, 2),
            ],
          ),
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(20, 0, 20, 32),
          child: const Column(
            children: [
              Text(
                "开通立享以下所有特权",
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 16,
                    fontWeight: FontWeight.w800),
              ),
            ],
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff8f8f8),
      appBar: AppBar(
        elevation: 0,
        title: const Text(
          "会员中心",
          style: TextStyle(
              color: Colors.white, fontWeight: FontWeight.w900, fontSize: 16),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          color: Colors.white, // 修改返回按钮颜色
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        backgroundColor: const Color(0xff13392F),
      ),
      body: vipData.vip!.isNotEmpty
          ? Column(
              children: [
                Expanded(
                  child: CustomScrollView(
                    slivers: [
                      SliverToBoxAdapter(child: _gmVIPTopWidget(vipData.vip!)),
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                            return _quanyiItemWidget(vipData.data![index]);
                          },
                          childCount: vipData.data!.length,
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(
                      20, 20, 20, 20 + ScreenUtil().bottomBarHeight),
                  child: InkWell(
                    onTap: () {
                      GMVIPModel data = vipData.vip![index];
                      if (data.des == '1') {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(
                            content:
                                Center(child: Text('您已经开通月会员用户,无需重复开通'),),
                            duration: Duration(seconds: 2),
                          ),
                        );
                      } else {
                        _gmToBuyProduct(data.pid!);
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      height: 50,
                      decoration: BoxDecoration(
                          color: const Color(0xff37A787),
                          borderRadius: BorderRadius.circular(25)),
                      child: const Text(
                        "立即充值",
                        style: TextStyle(
                            color: Color(0xffffffff),
                            fontSize: 15,
                            fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ),
              ],
            )
          : const Text("data"),
    );
  }
}
